/*
 * @Author: shengduiliang 1107722390@qq.com
 * @Date: 2024-05-05 13:19:12
 * @LastEditors: shengduiliang 1107722390@qq.com
 * @LastEditTime: 2024-05-05 17:36:08
 * @FilePath: /treasure/src/ui-components/image-picker/index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Image, View } from "@tarojs/components"
import { imageUtils } from "@/utils"
import to from 'await-to-js'
import Taro from "@tarojs/taro"
import { useCallback } from "react"
import pickerImage from './images/picker.png'
import deleleImage from './images/delete.png'
import CdnImage from "../cdn-image"
import './index.scss'


interface ImagePickerProps {
  images: string[]
  onChange: (images: string[]) => void
  count?: number // 最大上传数量
  title?: string // 上传按钮文案
  subTitle?: string // 上传按钮副文案
  mutiple?: boolean // 是否支持多选
}

const ImagePicker = ({ images, count, title, subTitle, mutiple = true, onChange }: ImagePickerProps) => {

  const handleAddImage = useCallback(async () => {
    // 上传图片
    const mutipleCount = count ? count - images.length : 9
    const chooseCount = mutiple ? mutipleCount : 1
    const localImageUrl = await imageUtils.chooseImages(chooseCount)
    if (!localImageUrl.length) return
    const [err, imageUrl] = await to(imageUtils.uploadImages(localImageUrl))
    if (err) {
      Taro.showToast({ title: '上传图片失败', icon: 'none' })
    }
    onChange([...images, ...(imageUrl || [])])
  }, [count, images, onChange])

  const handleDeleteImage = useCallback((index: number) => {
    const newImages = [...images]
    newImages.splice(index, 1)
    onChange(newImages)
  }, [images, onChange])

  const onLoadImage = useCallback((index: number) => {
    const previewImage = images.map(image => imageUtils.getCdnImage(image))
    Taro.previewImage({
      urls: previewImage,
      current: previewImage[index]
    })
  }, [images])

  return (
    <View className='image-picker pv-normal-mh-normal'>
      {
        title ? <View className='row-start-center'>
          <View className='image-picker-title text-primary-bold'>{title}</View>
          {
            subTitle && <View
              className='image-picker-sub-title secondary font-size-medium ml-medium'
            >
              ({subTitle})
            </View>
          }
        </View> : null 
      }
      <View className='image-picker-content row-start-center flex-wrap'>
        {
          images.map((item, index) => (
            <View key={index} className='image-picker-item mt-medium border'>
              <CdnImage src={item} mode='aspectFill' className='image-picker-img' onClick={() => onLoadImage(index)} />
              <View className='image-picker-delete' onClick={() => handleDeleteImage(index)}>
                <Image src={deleleImage} mode='aspectFill' />
              </View>
            </View>
          ))
        }
        {
          images.length < (count || 9) ? <View
            className='image-picker-item mt-medium border'
            onClick={handleAddImage}
          >
            <Image src={pickerImage} mode='aspectFill' className='image-picker-img' />
          </View> : null
        }
      </View>
    </View>
  )
}

export default ImagePicker